package com.atguigu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import org.apache.flink.api.java.tuple.Tuple2;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

public class DimUtil {

    public static JSONObject getDimInfo(Connection conn,String tableName,String id){
        Jedis jedis = JedisUtil.getJedis();
        String jedisKey=tableName+id;
        String jedisValue = jedis.get(jedisKey);
        JSONObject dimInfo =null;
        if (jedisValue==null){
            dimInfo = getDimInfo(conn, tableName, Tuple2.of("ID", id));
            jedis.setex(jedisKey,60*60*24*2,dimInfo.toJSONString());
        }else {
            dimInfo= JSON.parseObject(jedisValue);
        }
        jedis.close();
        return dimInfo;

    }

    public static JSONObject getDimInfo(Connection conn,String tableName, Tuple2<String,String>... fieldsAndValues){
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ")//select * from databases.table where id='10' and name='aaa'
                .append(GmallConfig.HBASE_SCHEMA)
                .append(".")
                .append(tableName)
                .append(" where ");
        for (int i = 0; i < fieldsAndValues.length; i++) {
            sql.append(fieldsAndValues[i].f0)
                    .append("='")
                    .append(fieldsAndValues[i].f1);
            if (i<fieldsAndValues.length-1){
                sql.append("' and ");
            }

        }
        sql.append("'");
        List<JSONObject> jsonObjects = PhoenixUtil.sqlQuery(conn, sql.toString(), JSONObject.class);
        if (jsonObjects.size()>0){
            return jsonObjects.get(0);
        }else {
            return new JSONObject();
        }
    }
}
